package com.feng.security.filter;

import cn.hutool.core.util.StrUtil;
import com.feng.common.utils.RedisCache;
import com.feng.security.config.SecurityConst;
import com.feng.security.domain.LoginUser;
import com.feng.security.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Feng
 * @since 2022/4/17 21:23
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader(SecurityConst.REQ_JWT_HEADER_KEY);
        if (StrUtil.isNotBlank(token)) {
            // 有携带token，解析
            String userId = null;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userId = claims.getSubject();
            } catch (Exception e) {
                // token非法
            }
            if (userId != null) {
                // token解析成功
                // 从Redis中获取用户信息
                String redisKey = SecurityConst.REDIS_JWT_KEY_PREFIX + userId;
                Long expire = redisCache.getExpire(redisKey);
                if (expire > 0) {
                    // 未过期
                    LoginUser loginUser = redisCache.getCacheObject(redisKey);
                    if (loginUser != null) {
                        // 验证成功，续期
                        if (expire < SecurityConst.JWT_DEFAULT_TTL) {
                            redisCache.expire(redisKey, SecurityConst.JWT_DEFAULT_TTL);
                        }
                        // 存入SecurityContextHolder
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, null);
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        }
        // 放行
        filterChain.doFilter(request, response);
    }
}
